package org.sang.controller;/*
 * @author  gaokecheng
 * @date 2019/9/11 14:53
 *
 *
 * */

import org.sang.bean.Editor;
import org.sang.bean.Hr;
import org.sang.common.FilePathProperties;
import org.sang.common.FinalString;
import org.sang.common.HrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ValidationException;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/editor")
public class EditorController {
    private  ResourceLoader resourceLoader;
    @Autowired
    private RedisTemplate redisTemplate;

    private  final FilePathProperties filePathProperties;

    public EditorController(ResourceLoader resourceLoader, FilePathProperties filePathProperties) {
        this.resourceLoader = resourceLoader;
        this.filePathProperties = filePathProperties;
    }

    @RequestMapping("/save")
    public Map<String, Object> editorSave(Editor ed) {
        Hr hr = HrUtils.getCurrentHr();
        System.out.println(ed + "传入");
        if (redisTemplate.hasKey(FinalString.EDITOR_KEY + hr.getUsername())) {
            redisTemplate.delete(FinalString.EDITOR_KEY + hr.getUsername());
        }
        redisTemplate.opsForValue().set(FinalString.EDITOR_KEY + hr.getUsername(), ed);
        Map result = new HashMap();
        result.put("status", "200");
        return result;
    }

    @RequestMapping("/search")
    public Map<String, Object> editorSearch() {
        Hr hr = HrUtils.getCurrentHr();
        Editor editor = (Editor) redisTemplate.opsForValue().get(FinalString.EDITOR_KEY + hr.getUsername());
        Map result = new HashMap();
        result.put("data", editor);
        return result;
    }

    @RequestMapping("/upload")
    public Map<String, Object> upload(@RequestParam("uploadFile") MultipartFile file) throws Exception {
        if (file == null) {
            throw new ValidationException("该文件不存在");
        }

        Map result = new HashMap();
        List<String> list = new ArrayList<>();
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            String filePath = filePathProperties.getPicTempFolderPath();
            String newName = UUID.randomUUID().toString() + "." + suffix;
            writeFile(file, filePath, newName);
            list.add("http://localhost:8080/editor/image?imageName="+newName);
            result.put("errno", "0");
            result.put("data", list);
        return result;
    }

    public String writeFile(MultipartFile multipartFile, String filePath, String newName) throws Exception {
        //新文件名
        //文件夹是否存在
        File tempFile = new File(filePath);
        if (!tempFile.exists()) {
            boolean isMkdirs = tempFile.mkdirs();
            if (!isMkdirs) {
                throw new ValidationException("创建文件夹失败");
            }
        }
        //创建文件
        File file = new File(tempFile, newName);
        if (!file.exists()) {
            boolean isCreateNewFile = file.createNewFile();
            if (!isCreateNewFile) {
                throw new ValidationException("创建文件失败");
            }
        }
        //写入磁盘
        multipartFile.transferTo(file);
        return file.getName();

    }
    @GetMapping("/image")
    public ResponseEntity getImage(String imageName) throws Exception {
        // 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
        String imagePath = filePathProperties.getPicTempFolderPath() + imageName;
        File file = new File(imagePath);
        if (!file.exists()) {
            throw new ValidationException("文件不存在");
        }
        return ResponseEntity.ok(resourceLoader.getResource("file:" + imagePath));
    }
}
